﻿using CQRSLearn.Features.Products.Dtos;
using CQRSLearn.Persistence;
using MediatR;

namespace CQRSLearn.Features.Products.Queries.Get
{
    public class GetProductQueryHandler : IRequestHandler<GetProductQuery, ProductDto>
    {
        private readonly AppDbContext context;

        public GetProductQueryHandler(AppDbContext context)
        {
            this.context = context;
        }

        public async Task<ProductDto> Handle(GetProductQuery request, CancellationToken cancellationToken)
        {
            var product = await context.Products.FindAsync(request.Id);
            if (product == null)
            {
                return null;
            }
            return new ProductDto(product.Id, product.Name, product.Description, product.Price);
        }
    }
}
